var p1Shooting; //I shot opponent
var p2Shooting; //Opponent shot me
var p1Name; //Your username
var p2Name; //Other player user name
var starter;
var gameId;
var p1ShootingArray = new Array(); //I shot opponent
var p2ShootingArray = new Array();//Opponent shot me
var bufferArray = new Array();
var ships;
var shipsArray = new Array();
var pause = 1000;
var count = 1;
var a;
var b;
var p1WreckedShipsCount = 0;
var p2WreckedShipsCount = 0;
var testList = new Array();
var timeOuts = new Array();

function saveReplay(){
	//Make string to array
	toArray(p1Shooting, p1ShootingArray);
	toArray(p2Shooting, p2ShootingArray);
	toArray(ships, shipsArray);
	//Make 3d array [[turn]]
	for (var i = 0; i < p1ShootingArray.length; i++){
		addTurnToBufferArray(p1ShootingArray[i]);
	}
	p1ShootingArray = bufferArray;
	bufferArray = new Array();
	for (var i = 0; i < p2ShootingArray.length; i++){
		addTurnToBufferArray(p2ShootingArray[i]);
	}
	p2ShootingArray = bufferArray;
	bufferArray = new Array();
	repGame = new replayGame(p1Name, p2Name, starter, p1ShootingArray, p2ShootingArray, shipsArray);
	var a = JSON.stringify(repGame);
	if(typeof(Storage)!=="undefined"){
		if(localStorage.getItem("gameReplays")){
			var item = localStorage.getItem("gameReplays");
			item = jQuery.parseJSON(item);
			item.push(a);
			localStorage.setItem("gameReplays", JSON.stringify(item));
		}
		else{
			var list = new Array();
			list.push(a);
			localStorage.setItem("gameReplays", JSON.stringify(list));
		}
	  }
	else
	  {
	  // Sorry! No web storage support..
	  }
}

function loadReplayList(){
	if(typeof(Storage)!="undefined"){
		var gameL = jQuery.parseJSON(localStorage.getItem("gameReplays"));
		var finalGameL = new Array();
		if (gameL != null){
			for (var i = gameL.length - 1; i > 0; i--){
				finalGameL.push(jQuery.parseJSON(gameL[i]));
			}
		}
		return finalGameL;
	}
	else{
		
	}
}

function generateReplayList(){
	var gameList = loadReplayList();
	var games = "<table id='replayListTable' border='0'><tr><th>You</th><th>Opponent</th></tr>";
	for (var i = 0; i < gameList.length; i++){
		games += "<tr id='tr" + i + "'><td>" + gameList[i].p1Name + "</td><td>" + gameList[i].p2Name +"</td></tr>";
	}
	document.getElementById("rRightPane").innerHTML = games + "</table>";
}

function replay(id){
	resetBoard();
	if (id != undefined){
		$("#errorArea").show("fast");
		document.getElementById("errorArea").innerHTML = "Preparing...";
		var gameId = id;
		var game = loadReplayList()[gameId[2]];
		var name1;
		var name2;
		var mTId;
		var oTId;
		var listLen = Math.min(game.p1ShootingArray.length, game.p2ShootingArray.length);
		setTimeout(function(){drawShips(game.shipsArray);}, 1000);
		
		if (game.starter == game.p1Name){
			mTId = 3;
			oTId = 4;
			a = game.p1ShootingArray;
			b = game.p2ShootingArray;
			name1 = game.p1Name;
			name2 = game.p2Name;
		}
		else{
			mTId = 4;
			oTId = 3;
			a = game.p2ShootingArray;
			b = game.p1ShootingArray;
			name2 = game.p1Name;
			name1 = game.p2Name;
		}
		for(var turn = 0; turn < listLen; turn++){
			//Alustaja tulistab
			for (var shoot = 0; shoot < a[turn].length; shoot++){
				if(a[turn][shoot][2] == 0){
					timeOuts[count] = setTimeout("markAsMissed(" + mTId +", " + a[turn][shoot][0] +", " + a[turn][shoot][1] + ", '" + name1 + "', '" + name2 + "' )", count * pause);
					count += 1;
				}
				else if(a[turn][shoot][3] == 0){
					timeOuts[count] = setTimeout("markAsHit(" + mTId +", " + a[turn][shoot][0] +", " + a[turn][shoot][1] + ")", count * pause);
					count += 1;
				}
				else if (a[turn][shoot][3] == 1){
					timeOuts[count] = setTimeout("markAsHit(" + mTId +", " + a[turn][shoot][0] +", " + a[turn][shoot][1] + ")", count * pause);
					timeOuts[count] = setTimeout("markAsWrecked('a', " + mTId +", '" + a[turn][shoot][2] + "', '" + name1 + "', '" + name2 + "')", count * pause);
					count += 1;
				}
			}

			//Teine tulistab
			for (var shoot = 0; shoot < b[turn].length; shoot++){
				
				if(b[turn][shoot][2] == 0){
					timeOuts[count] = setTimeout("markAsMissed(" + oTId +", " + b[turn][shoot][0] +", " + b[turn][shoot][1] + ", '" + name1 + "', '" + name2 + "')", count * pause);
					count += 1;
				}
				else if(b[turn][shoot][3] == 0){
					timeOuts[count] = setTimeout("markAsHit(" + oTId +", " + b[turn][shoot][0] +", " + b[turn][shoot][1] + ")", count * pause);
					count += 1;
				}
				else if(b[turn][shoot][3] == 1) {
					timeOuts[count] = setTimeout("markAsHit(" + oTId +", " + b[turn][shoot][0] +", " + b[turn][shoot][1] + ")", count * pause);
					timeOuts[count] = setTimeout("markAsWrecked('b', " + oTId +", '" + b[turn][shoot][2] + "', '" + name1 + "', '" + name2 + "')", count * pause);
					count += 1;
				}				
			}
		}
	}
	else{
		document.getElementById("errorArea").innerHTML = "Choose replay";
	}
	
}

function drawShips(list){
	for(var row = 0; row < list.length; row++){
		for (var col = 0; col < list[row].length; col++){
			if(list[row][col].length > 1){
				$("#4" + row.toString() + col.toString()).addClass("replayShip");
			}
		}
	}
}

function resetBoard(){
	count = 1;
	for(var i = 0; i < timeOuts.length; i++){
		clearTimeout(timeOuts[i]);
	}
	$("#errorArea").hide("fast");
	resetBoardCss();
}

function resetBoardCss(){
	for (var i = 0; i < 10; i++){
		for (var j = 0; j < 10; j++){
			$("#3" + i + j).removeClass();
			$("#4" + i + j).removeClass();
			$("#3" + i + j + " .explosion").hide(0);
			$("#4" + i + j + " .explosion").hide(0);
			$("#3" + i + j + " .wrecked").hide(0);
			$("#4" + i + j + " .wrecked").hide(0);
			$("#3" + i + j).addClass("opponent");
			$("#4" + i + j).addClass("player");
		}
	}
}

/*function clearLocalStorage(){
	if(typeof(Storage)!=="undefined"){
		localStorage.setItem("gameReplays", JSON.stringify(new Array()));
	}
}*/

function markAsMissed(boardId, row, col, name1, name2){
	$("#" + boardId + row.toString() + col.toString()).addClass("shootedd");
	if (boardId == 3){
		document.getElementById("errorArea").innerHTML = name2 + "'s turn";
	}
	else{
		document.getElementById("errorArea").innerHTML = name1 + "'s turn";
	}
}

function markAsHit(boardId, row, col){
	$("#" + boardId + row.toString() + col.toString()).addClass("hit");
	$("#" + boardId + row.toString() + col.toString() + " .explosion").show("explode","slow");
}

function markAsWrecked(ar, boardId, shipId, name1, name2){
	var list;
	if (ar == 'b'){
		list = b;
		p1WreckedShipsCount += 1;
		if(p1WreckedShipsCount == 3){
			document.getElementById("errorArea").innerHTML = name2 + " won!";
			$("#errorArea").show("fast");
		}
	}
	else{
		list = a;
		p2WreckedShipsCount += 1;
		if(p2WreckedShipsCount == 1){
			document.getElementById("errorArea").innerHTML = name1 + " won!";
			$("#errorArea").show("fast");
		}
	}
	for(var turn = 0; turn < list.length; turn++){
		for(var shoot = 0; shoot < list[turn].length; shoot++){
			if(list[turn][shoot][2] == shipId){
				$("#" + boardId + list[turn][shoot][0].toString() + list[turn][shoot][1].toString() + " .explosion").hide("fast");
				$("#" + boardId + list[turn][shoot][0].toString() + list[turn][shoot][1].toString() + " .wrecked").show("explode","slow");
				$("#" + boardId + list[turn][shoot][0].toString() + list[turn][shoot][1].toString()).removeClass("hit");
			}
		}
	}
}

function addTurnToBufferArray(turnList){
	bufferArray.push(new Array());
	for (var j = 0; j < turnList.length; j++){
		if (j % 4 == 0){
			bufferArray[bufferArray.length-1].push(new Array());
		}
		bufferArray[bufferArray.length-1][bufferArray[bufferArray.length-1].length-1].push(turnList[j]);
	}
}

function toArray(string, array){
	var s ="";
	var count = 0;
	for (var i = 0; i < string.length; i++){
		if (string[i] == "[" && i != 0){
			array.push(new Array());
		}
		else if (string[i] == '"' && count % 2 == 0) {
			count += 1;
		}
		else if (string[i] == '"' && count % 2 == 1){
			array[array.length-1].push(s);
			s = "";
			count += 1;
		}
		else if(count % 2 == 1){
			s += string[i];
		}
	}
}

